<template>
  <div v-loading.fullscreen.lock="uploadFileSize > 0" class="app-container">
    <!-- 开课选择卡片 -->
    <el-card>
      <div slot="header">选择开设课程</div>
      <div>
        <el-cascader
          v-model="courseId"
          :options="dropDownData.courseSchedule"
          :show-all-levels="false"
          :props="{emitPath:false}"
        />
      </div>
    </el-card>
    <!-- 开课资源管理卡片 -->
    <el-card style="margin-top: 20px;height: 800px;">
      <el-row>
        <!-- 资源类型导航菜单 -->
        <el-col :span="4">
          <el-menu
            active-text-color="#1989fa"
          >
            <el-menu-item index="1" @click=" getFileListByType(-1)">
              <template slot="title">
                <SvgIcon icon-class="crm-all" />
                全部文件
              </template>
            </el-menu-item>
            <el-menu-item index="2" @click=" getFileListByType(0)">
              <template slot="title">
                <SvgIcon icon-class="crm-image" />
                图片
              </template>
            </el-menu-item>
            <el-menu-item index="3" @click=" getFileListByType(1)">
              <template slot="title">
                <SvgIcon icon-class="crm-vedio" />
                视频
              </template>
            </el-menu-item>
            <el-menu-item index="4" @click=" getFileListByType(2)">
              <template slot="title">
                <SvgIcon icon-class="crm-document" />
                文档
              </template>
            </el-menu-item>
            <el-menu-item index="5" @click=" getFileListByType(3)">
              <template slot="title">
                <SvgIcon icon-class="crm-audio" />
                音频
              </template>
            </el-menu-item>
            <el-menu-item index="6" @click=" getFileListByType(4)">
              <template slot="title">
                <SvgIcon icon-class="crm-archive" />
                压缩包
              </template>
            </el-menu-item>
            <el-menu-item index="7" @click=" getFileListByType(5,'其它')">
              <template slot="title">
                <SvgIcon icon-class="crm-other" />
                其它
              </template>
            </el-menu-item>
          </el-menu>
        </el-col>
        <!-- 资源详情列表 -->
        <el-col :span="20">
          <!-- 资源管理菜单 -->
          <el-card>
            <el-button v-if="resouceMangeShow" type="primary" @click="openUploadDialog">上传文件</el-button>
            <el-button v-if="resouceMangeShow" type="primary" plain @click="openCreateFolderMsgBox">新建文件夹</el-button>
            <el-button v-if="resourceDeleteBtnShow" type="danger" plain @click="deleteFiles">删除</el-button>
          </el-card>
          <!-- 资源目录导航菜单 -->
          <el-card>
            <el-link :underline="false">
              <i class="el-icon-arrow-left" />
            </el-link>
            <el-link :underline="false">
              <i class="el-icon-arrow-right" style="margin-left: 10px" />
            </el-link>
            <el-link :underline="false">
              <i class="el-icon-refresh-right" style="margin-left: 10px" />
            </el-link>
            <el-breadcrumb
              separator-class="el-icon-arrow-right"
              style="margin-left: 10px;display: inline-block;position: relative;top: 3px;"
            >
              <el-breadcrumb-item v-for="(folder,idx) in folderStack" :key="folder.folderId">
                <el-link :underline="false" @click="jumpFolder(idx)">{{ folder.folderName }}</el-link>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </el-card>
          <!-- 资源列表 -->
          <el-table
            :data="fileList"
            :height="600"
            @selection-change="fileSelectChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="文件名">
              <template slot-scope="scope">
                <el-link v-if="scope.row.isFolder" :underline="false" @click="changeFolder(scope.row)">
                  <SvgIcon :icon-class="getIconName(scope.row)" />
                  <span style="margin-left: 10px">{{ scope.row.fileName }}</span>
                </el-link>
                <el-link v-else :underline="false" @click="downloadFile(scope.row.url)">
                  <SvgIcon :icon-class="getIconName(scope.row)" />
                  <span style="margin-left: 10px">{{ scope.row.fileName }}</span>
                </el-link>
              </template>
            </el-table-column>
            <el-table-column prop="typeName" label="类型" />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-link :underline="false" style="margin-left: 10px" @click="renameFile(scope.row)">重命名</el-link>
                <el-link :underline="false" style="margin-left: 10px" @click="deleteFile(scope.row)">删除</el-link>
                <el-link v-if="!scope.row.isFolder" :underline="false" style="margin-left: 10px" @click="downloadFile(scope.row.url)">下载</el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
    <!-- 课程资源文件上传Dialog -->
    <el-dialog
      :title="'上传文件'"
      width="50%"
      :visible.sync="uploadDialogShow"
      :before-close="handleUploadDialogClose"
    >
      <el-upload
        ref="resourceUpload"
        width="100%"
        class="upload-demo"
        drag
        :limit="3"
        action="http://aaa"
        :http-request="handleUploadFile"
        :before-upload="handleBeforeUpload"
        :auto-upload="false"
        multiple
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">单次最多可上传三个文件,且每个文件不超过50MB</div>
      </el-upload>
      <el-divider />
      <div style="height: 20px;">
        <el-button type="primary" style="float: right;margin-left: 20px;" @click="confirmUploadFile">确认上传</el-button>
        <el-button style="float: right;" @click="handleUploadDialogClose">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SvgIcon from '@/components/SvgIcon'
import { getFileIconName } from '@/utils/file'
import { getRootFolder, getFilesByFolder, getFilesByType, createDir, deleteFilesById, deleteFoldersById,
  renameFile, renameFolder, createFile } from '@/api/ms/course/teach/resouce'
import { uploadCourseResource } from '@/api/ms/oss'
import { getCourseScheduleDropDownGroupByCourse } from '@/api/ms/dropdown'

export default {
  name: 'CourseResourse',
  components: { SvgIcon },
  data() {
    return {
      dropDownData: {
        // 开课候选列表
        courseSchedule: []
      },
      fileList: [// 当前文件(夹)列表
        // { id: 1, fileName: '文件1.mp4', typeId: 1, typeName: '视频', isFolder: false, url: 'http://aaaa' },
      ],
      folderStack: [ // 目录路径栈
        // { id: -1, folderName: '全部文件' }
      ],
      nowFileType: -1, // 当前检索文件类型
      courseId: 1, // 当前资源的开课编号
      resouceMangeShow: true, // 是否显示新建文件夹按钮
      resourceDeleteBtnShow: false, // 是否显示删除按钮
      selectedFiles: [], // 选中的文件(夹)
      rootFolderName: '', // 根资源目录名称
      uploadDialogShow: false, // 是否显示文件上传Dialog
      uploadFileSize: 0 // 正在上传的文件数量
    }
  },
  computed: {
    currentFolderId() { // 获取当前文件夹的id
      const len = this.folderStack.length
      return this.folderStack[len - 1].id
    },
    folderFullPath() { // 获取当前的目录全路径
      let path = '/' + this.rootFolderName
      for (let index = 1; index < this.folderStack.length; index++) {
        const folder = this.folderStack[index]
        path += '/' + folder.folderName
      }
      return path
    }
  },
  watch: {
    courseId(val) {
      this.getFileListByType(this.nowFileType)
    }
  },
  mounted() {
    // 获取下拉数据
    this.getDropDownData()
    // 获取选中的开课下的根文件夹信息
    this.getRootFolderByCourse()
  },
  methods: {
    // 获取下拉数据
    getDropDownData() {
      // 获取开课按学院分组数据
      getCourseScheduleDropDownGroupByCourse().then(({ data }) => {
        this.dropDownData.courseSchedule = data
      })
    },
    // 获取选中的开课下的根文件夹信息
    getRootFolderByCourse() {
      getRootFolder(this.courseId).then(({ data }) => {
        this.folderStack = []
        //   导航添加目录
        this.folderStack.push({
          id: data.id,
          folderName: '全部文件'
        })
        this.rootFolderName = data.folderName
        // 获取根目录下所有资源
        this.getFileList(data.id)
      })
    },
    // 获取当前目录下的所有文件资源
    getFileList(folderId) {
      getFilesByFolder(folderId).then(({ data }) => {
        this.fileList = data
      })
    },
    // 获取根文件夹显示名称
    getRootFolderShowName(idx) {
      switch (idx) {
        case -1:
          return '全部文件'
        case 0:
          return '图片'
        case 1:
          return '视频'
        case 2:
          return '文档'
        case 3:
          return '音频'
        case 4:
          return '压缩包'
        default:
          return '其它'
      }
    },
    // 获取指定分类下的所有资源
    getFileListByType(typeId) {
      this.nowFileType = typeId
      if (typeId === -1) {
        this.getRootFolderByCourse()
        // 显示资源管理菜单
        this.resouceMangeShow = true
      } else {
        const reqData = {
          courseId: this.courseId,
          typeId: typeId
        }
        getFilesByType(reqData).then(({ data }) => {
          this.fileList = data
          this.folderStack = []
          //   导航添加目录
          this.folderStack.push({
            id: -1,
            folderName: this.getRootFolderShowName(typeId)
          })
          // 不显示资源管理菜单
          this.resouceMangeShow = false
        })
      }
    },
    // 打开新建文件夹对话框
    openCreateFolderMsgBox() {
      this.$prompt('请输入文件夹名称:', '新建文件夹', {
        inputPattern: /^[^\\/:*?"<>|]+$/,
        inputErrorMessage: '文件夹名称不能为空，且不能包含\\/:*?"<>|字符'
      }).then(({ value }) => {
        const reqData = {
          folderName: value,
          isRoot: false,
          parentFolderId: this.currentFolderId
        }
        createDir(reqData).then(({ message }) => {
          this.$message.success('新建文件夹成功')
          // 刷新数据
          this.refreshData()
        })
      }).catch(() => {
        this.$message.info('取消创建文件夹')
      })
    },
    // 刷新数据
    refreshData() {
      this.getFileList(this.currentFolderId)
    },
    // 获取文件icon名称
    getIconName(file) {
      return getFileIconName(file.typeId, file.fileName)
    },
    // 下载文件
    downloadFile(fileUrl) {
      window.open(fileUrl)
    },
    // 重命名文件(夹)
    renameFile(file) {
      this.$prompt('请输入新的文件(夹)名称:', '重命名文件(夹)', {
        inputPattern: /^[^\\/:*?"<>|]+$/,
        inputErrorMessage: '文件(夹)新名称不能为空，且不能包含\\/:*?"<>|字符'
      }).then(({ value }) => {
        const reqData = {
          id: file.id,
          newName: value
        }
        if (file.isFolder) {
          renameFolder(reqData).then(() => {
            this.$message.success('重命名文件(夹)成功')
            // 刷新数据
            this.refreshData()
          })
        } else {
          renameFile(reqData).then(() => {
            this.$message.success('重命名文件(夹)成功')
            // 刷新数据
            this.refreshData()
          })
        }
      }).catch(() => {
        this.$message.info('取消重命名文件(夹)')
      })
    },
    // 删除文件(夹)
    deleteFile(file) {
      // 构造idList
      const ids = []
      ids.push(file.id)
      this.$confirm('是否确认删除？', '提示').then(() => {
        if (file.isFolder) {
          deleteFoldersById(ids).then(() => {
            this.$message.success('已成功删除')
            this.refreshData()
          })
        } else {
          deleteFilesById(ids).then(() => {
            this.$message.success('已成功删除')
            this.refreshData()
          })
        }
      }).catch(() => {
        this.$message.info('删除已取消')
      })
    },
    // 进入文件夹
    changeFolder(fileFolder) {
      this.getFileList(fileFolder.id)
      //   导航添加目录
      this.folderStack.push({
        id: fileFolder.id,
        folderName: fileFolder.fileName
      })
    },
    // 导航目录跳转
    jumpFolder(idx) {
      // 如果下标为最后一个，无需跳转目录
      if (idx === this.folderStack.length - 1) {
        return
      }
      // 获取跳转目标目录下的资源
      const folder = this.folderStack[idx]
      this.getFileList(folder.id)
      // 截取前面的目录
      this.folderStack = this.folderStack.slice(0, idx + 1)
    },
    // 处理文件列表勾选change
    fileSelectChange(rows) {
      this.selectedFiles = rows
      this.resourceDeleteBtnShow = rows.length > 0
    },
    // 批量删除文件(夹)
    deleteFiles() {
      // 将文件和文件夹分为两组
      const folderIds = this.selectedFiles.filter(f => f.isFolder).map(f => f.id)
      const fileIds = this.selectedFiles.filter(f => !f.isFolder).map(f => f.id)
      this.$confirm('是否确认删除？', '提示').then(() => {
        deleteFilesById(fileIds).then(() => {
          deleteFoldersById(folderIds).then(() => {
            this.$message.success('已成功删除')
            this.refreshData()
          })
        })
      }).catch(() => {
        this.$message.info('删除已取消')
      })
    },
    // 打开上传对话框
    openUploadDialog() {
      this.uploadDialogShow = true
    },
    // 处理文件上传对话框关闭
    handleUploadDialogClose() {
      this.uploadDialogShow = false
      // 清空上传列表
      this.$refs.resourceUpload.clearFiles()
      this.uploadFileSize = 0
    },
    // 上传文件确认按钮点击
    confirmUploadFile() {
      this.$refs.resourceUpload.submit()
    },
    // 文件上传前处理
    handleBeforeUpload(file) {
      const limit5M = file.size / 1024 / 1024 <= 1
      if (!limit5M) {
        this.$message.error(`文件"${file.name}"已超过50MB`)
      }
      const flag = limit5M
      if (flag) {
        this.uploadFileSize++
      }
      return flag
    },
    // 文件上传处理
    handleUploadFile(form) {
      const formData = new FormData()
      const fileName = form.file.name
      formData.append('file', form.file)
      formData.append('fileName', fileName)
      formData.append('folderName', this.folderFullPath)
      uploadCourseResource(formData).then((res) => {
        // 将文件信息保存到数据库
        const reqData = {
          courseId: this.courseId,
          resourceName: fileName,
          folderId: this.currentFolderId,
          resourceUrl: res.data.resourceUrl
        }
        createFile(reqData).then(() => {
          this.$message.success(res.message)
          this.uploadFileSize--
          if (this.uploadFileSize === 0) {
            // 资源全部上传完成，关闭对话框
            this.handleUploadDialogClose()
            // 刷新资源
            this.refreshData()
          }
        }).catch(() => {
          this.uploadFileSize--
        })
      }).catch(() => {
        this.uploadFileSize--
      })
    }
  }
}
</script>

<style scpoed>

</style>
